package com.scau402.system.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.scau402.common.annotation.DataScope;
import com.scau402.common.utils.SecurityUtils;
import com.scau402.config.MockConfig;
import com.scau402.system.service.IWmsJadeImageService;
import com.scau402.system.service.IWmsJadeService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.scau402.common.annotation.Log;
import com.scau402.common.core.controller.BaseController;
import com.scau402.common.core.domain.AjaxResult;
import com.scau402.common.enums.BusinessType;
import com.scau402.system.domain.WmsJadeFeature;
import com.scau402.system.service.IWmsJadeFeatureService;
import com.scau402.common.utils.poi.ExcelUtil;
import com.scau402.common.core.page.TableDataInfo;
import org.springframework.web.client.RestTemplate;

/**
 * 翡翠特征管理Controller
 * 
 * @author ruoyi
 * @date 2023-07-17
 */
@RestController
@RequestMapping("/system/jadeFeature")
public class WmsJadeFeatureController extends BaseController
{
    @Autowired
    private IWmsJadeFeatureService wmsJadeFeatureService;

    @Autowired
    private IWmsJadeImageService wmsJadeImageService;

    @Autowired
    private IWmsJadeService wmsJadeService;

    @Autowired
    private MockConfig mockConfig;

    private final RestTemplate restTemplate;

    public WmsJadeFeatureController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }


    /**
     * 查询翡翠特征管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:jadeFeature:list')")
    @DataScope(tenantAlias = "t", userAlias = "u")
    @GetMapping("/list")
    public TableDataInfo list(WmsJadeFeature wmsJadeFeature)
    {
        startPage();
        List<WmsJadeFeature> list = wmsJadeFeatureService.selectWmsJadeFeatureList(wmsJadeFeature);
        return getDataTable(list);
    }

    /**
     * 导出翡翠特征管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:jadeFeature:export')")
    @Log(title = "翡翠特征管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WmsJadeFeature wmsJadeFeature)
    {
        List<WmsJadeFeature> list = wmsJadeFeatureService.selectWmsJadeFeatureList(wmsJadeFeature);
        ExcelUtil<WmsJadeFeature> util = new ExcelUtil<WmsJadeFeature>(WmsJadeFeature.class);
        util.exportExcel(response, list, "翡翠特征管理数据");
    }

    /**
     * 获取翡翠特征管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:jadeFeature:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(wmsJadeFeatureService.selectWmsJadeFeatureById(id));
    }

    /**
     * 新增翡翠特征管理
     */
    @PreAuthorize("@ss.hasPermi('system:jadeFeature:add')")
    @Log(title = "翡翠特征管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WmsJadeFeature wmsJadeFeature)
    {
        wmsJadeFeature.setCreateBy(getUsername());
        return toAjax(wmsJadeFeatureService.insertWmsJadeFeature(wmsJadeFeature));
    }

    /**
     * 修改翡翠特征管理
     */
    @PreAuthorize("@ss.hasPermi('system:jadeFeature:edit')")
    @Log(title = "翡翠特征管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WmsJadeFeature wmsJadeFeature)
    {
        return toAjax(wmsJadeFeatureService.updateWmsJadeFeature(wmsJadeFeature));
    }

    /**
     * 删除翡翠特征管理
     */
    @PreAuthorize("@ss.hasPermi('system:jadeFeature:remove')")
    @Log(title = "翡翠特征管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(wmsJadeFeatureService.deleteWmsJadeFeatureByIds(ids));
    }

    /**
     * 获取库中匹配翡翠
     * @param params
     *     imageIds 要匹配的图像主键ID
     * @return 匹配结果
     */
    @PreAuthorize("@ss.hasPermi('system:jadeFeature:add')")
    @PostMapping("/match")
    public AjaxResult match(@RequestBody String params)
    {
        if (mockConfig.isMockMatchEnabled()) {
            return AjaxResult.success("mock");
        }
        // 转换 source_ids 为 list 格式
        JSONObject params_json =  JSON.parseObject(params);
        JSONArray jsonArray = params_json.getJSONArray("imageIds");
        List<Long> source_ids = JSONArray.parseArray(jsonArray.toJSONString(), Long.class);

        // 获取在库的 status 为 0（在库）的翡翠货品图像主键ID
        List<Long> list = wmsJadeService.selectInstockJadeImageIdList(SecurityUtils.getLoginUser().getTenantId());

        // 判断在库库存是否为 0
        if(list.size() == 0) {
            AjaxResult ajax = AjaxResult.error();
            ajax.put("error", "当前在库翡翠数量为0");
            return ajax;
        }

        // 调用匹配接口
        JSONObject post_params = new JSONObject();
        post_params.put("source_ids", source_ids);
        post_params.put("search_list", list);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(post_params.toJSONString(), headers);
        JSONObject jsonObject =  JSON.parseObject(restTemplate.postForObject("http://cyolov8:8001/match", request, String.class));
        AjaxResult ajax = AjaxResult.success();
        ajax.put("match_result", jsonObject);
        return ajax;
    }
}
